package com.example.day15_7_15_1.activity;

import android.Manifest;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.example.day15_7_15_1.R;
import com.example.day15_7_15_1.adapter.InfoVpAdapter;
import com.example.day15_7_15_1.fragment.DownloadFragment;
import com.example.day15_7_15_1.fragment.HomeFragment;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TextView tvToolbar;
    private ViewPager vp;
    private TabLayout tab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityCompat.requestPermissions(this,new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        },200);
        initView();
    }

    private void initView() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tvToolbar = (TextView) findViewById(R.id.tv_toolbar);
        vp = (ViewPager) findViewById(R.id.vp);
        tab = (TabLayout) findViewById(R.id.tab);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        tvToolbar.setText("首页");
        HomeFragment homeFragment = new HomeFragment();
        DownloadFragment downloadFragment = new DownloadFragment();
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(homeFragment);
        fragments.add(downloadFragment);
        InfoVpAdapter infoVpAdapter = new InfoVpAdapter(getSupportFragmentManager(), fragments);
        vp.setAdapter(infoVpAdapter);
        tab.setupWithViewPager(vp);
        final String[] strings = new String[]{"首页","下载"};
        for (int i = 0; i < fragments.size(); i++) {
            tab.getTabAt(i).setCustomView(getView(strings[i]));
        }
        tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tvToolbar.setText(strings[tab.getPosition()]);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private View getView(String string) {
        TextView textView = new TextView(this);
        textView.setTextSize(20);
        textView.setGravity(Gravity.CENTER);
        textView.setText(string);
        return textView;
    }

}
